package com.topnav.mc.runner;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.js.lib.cache.Cache;
import com.js.lib.cache.SysCache;
import com.js.lib.utils.JsonUtil;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DeviceChannel;
import com.topnav.mc.admin.entity.GbServer;
import com.topnav.mc.admin.entity.SystemConfig;
import com.topnav.mc.admin.service.*;
import com.topnav.mc.common.Constant;
import com.topnav.mc.gbserverapi.GbServerApi;
import com.topnav.mc.listener.DeviceExpireLocalCachListener;
import com.topnav.mc.lock.TestJob;
import com.topnav.mc.system.ISystemMonitorService;
import com.topnav.mc.uitls.GbServerUtil;
import com.topnav.mc.uitls.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

@Order(1)
@Slf4j
@Component
public class SystemRunner implements ApplicationRunner {
    @Value("${wvp-server:none}")
    private String wvpServer;

    @Resource(name="sysCache")
    private Cache cache;
    @Autowired
    private IGbServerService gdbService;
    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IFenceService fenceService;
    @Autowired
    private IDeviceChannelService deviceChannelService;
    @Autowired
    private ISystemConfigService systemConfigService;
    @Autowired
    private DeviceExpireLocalCachListener deviceExpireLocalCachListener;
    @Resource
    private GbServerApi api;
    @Autowired
    private IUserService userService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //所有设备和通道设成离线
        UpdateWrapper<Device> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("online",false);
        updateWrapper.eq("cate",2).or().eq("cate",3);
        deviceService.update(updateWrapper);
        UpdateWrapper<DeviceChannel> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.set("status",0);
        deviceChannelService.update(updateWrapper1);

        //测试WVP是否在配置文件里配置,如果已配置则尝试连接，连接不成功则取数据库里的GbServer
        //偿试连接，如果成功则更新GbServer表
        GbServerUtil.remove();
        if (!"none".equals(wvpServer)){
            String url = "http://" + wvpServer;
            try{
                //尝试连接
                String resultStr = api.info(url);
                JSONObject result = JSONObject.parseObject(resultStr);
                JSONObject data = result.getJSONObject("data");
                if (data != null){
                    JSONObject sipConfig = data.getJSONObject("sipConfig");
                    if (sipConfig != null){
                        QueryWrapper<GbServer> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("code",sipConfig.getString("id"));
                        GbServer gbServer = gdbService.getOne(queryWrapper,false);
                        if (gbServer == null){
                            gbServer = new GbServer();
                            gbServer.setCreateTime(new Date());
                        }
                        gbServer.setCode(sipConfig.getString("id"));
                        if (gbServer.getName() == null)
                            gbServer.setName(sipConfig.getString("id"));
                        if (sipConfig.get("showIp") != null)
                            gbServer.setHost(sipConfig.getString("showIp"));
                        else
                            gbServer.setHost(sipConfig.getString("ip"));

                        gbServer.setPort(sipConfig.getString("port"));
                        gbServer.setDomain(sipConfig.getString("domain"));
                        gbServer.setPasswrd(sipConfig.getString("password"));
                        gbServer.setApiPort(wvpServer.split(":")[1]);
                        gbServer.setLocalIpPort(wvpServer);
                        gbServer.setUpdateTime(new Date());
                        gdbService.saveOrUpdate(gbServer);
                        GbServerUtil.set(wvpServer);
                    }
                }
            }catch (Exception e){
                if (e.toString().indexOf("Failed to connect to")>-1){
                    log.error(e.toString() + ": " + wvpServer);
                }
            }
        }
        gdbService.saveAllToCache();
        log.info("##: 国标服务信息读入缓存......");
        systemConfigService.saveAllToCache();
        log.info("##: 系统配置信息读入缓存......");
        deviceService.saveAllToCache();
        log.info("##: 设备信息读入缓存......");
        fenceService.saveAllToCache();
        log.info("##: 围栏信息读入缓存......");
        organizationService.saveAllToCache();
        log.info("##: 部门信息读入缓存......");
        userService.saveAllToCache();
        log.info("##: 用户信息读入缓存......");

        //临听缓存
        if ("local".equals(cache.getCacheType())){
            cache.addListener(deviceExpireLocalCachListener);
        }

        //定时清理过期键
        cache.autoClearExpire(10L);


   }

}
